
package com.scalar.chiptrack.users.actions;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.scalar.ScalarException;
import com.scalar.chiptrack.ChipTrackAction;
import com.scalar.chiptrack.commons.Constants;
import com.scalar.chiptrack.commons.SessionKeys;
import com.scalar.chiptrack.users.User;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.users.forms.MaintainUserForm;
import com.scalar.chiptrack.utils.ConfigManager;

public final class MaintainUserAction extends ChipTrackAction {

    private static String SOURCE_PAGE = "/maintainUser.do";

    public ActionForward execute (ActionMapping mapping,
                                  ActionForm form,
                                  HttpServletRequest request,
                                  HttpServletResponse response)
                                  throws Exception {

        HashMap info = new HashMap();
        request.setAttribute (SessionKeys.INFO_MESSAGES, info);

        HashMap errors = new HashMap();
        request.setAttribute (SessionKeys.ERROR_MESSAGES, errors);

        try {
            HttpSession session = request.getSession ();
            User user = null;

            if ((user = (User) session.getAttribute (SessionKeys.USER_KEY)) == null) {
                ActionForward actionForward = new ActionForward (ConfigManager.getDefaultLoginPage() + "?sourcePage=" + SOURCE_PAGE);
                return actionForward;
            }

            // Check if its a request to delete the user
            if ("delete".equalsIgnoreCase(request.getParameter("useraction")) == true) {
                String userToDelete = request.getParameter("username");
                if ((userToDelete != null) && (userToDelete.trim().length() != 0)) {
                    try {
                        UserDAO.deleteUser (userToDelete);
                        info.put (userToDelete + " has been disabled", null);
                    }
                    catch (ScalarException se) {
                        // problem with database
                        se.printStackTrace ();
                        errors.put ("Internal Server Error", "Could not delete \"" + userToDelete + "\"");
                    }
                }
            }


            // ACTIVATE THE USER
            else if ("activate".equalsIgnoreCase(request.getParameter("useraction")) == true) {
                String userToActivate = request.getParameter("username");
                if ((userToActivate != null) && (userToActivate.trim().length() != 0)) {
                    try {
                        UserDAO.activateUser (userToActivate);
                        info.put (userToActivate + " has been activated", null);
                    }
                    catch (ScalarException se) {
                        // problem with database
                        se.printStackTrace ();
                        errors.put ("Internal Server Error", "Could not activate \"" + userToActivate + "\"");
                    }
                }
            }


            ArrayList userList = null;
            ArrayList groupList = null;


            if (form != null) {
                MaintainUserForm maintainUserForm = (MaintainUserForm) form;

                String firstName = maintainUserForm.getFirstName();
                String lastName = maintainUserForm.getLastName();
                String groupName = maintainUserForm.getGroupName();

                //System.out.println("group name  "+groupName);

                if( (((firstName != null) && (firstName.trim().length() != 0)) || ( (lastName != null) && (lastName.trim().length() != 0) )) && ((groupName != null) &&( (groupName.trim().length() != 0)) && !("-1".equalsIgnoreCase(groupName)) ))
                {
					userList = UserDAO.loadUsersByFirstNameLastNameAndGroup (firstName, lastName, groupName, true );
                }
                // Load users by first name and last name
                else if (((firstName != null) && (firstName.trim().length() != 0))|| ((lastName != null) && (lastName.trim().length() != 0))) {

                    userList = UserDAO.loadUsersByFirstNameAndLastName (firstName, lastName, true /*load expired and disabled users*/);
                }

                // Load user by group name
                else if (!("-1".equalsIgnoreCase(groupName)) && (groupName != null) && (groupName.trim().length() != 0)) {

                    userList = UserDAO.loadUsersByGroupName (groupName, true /*load expired and disabled users*/);
                }

                // Load all users
                else {
                    userList = UserDAO.loadAllUsers(true/*load expired and disabled users*/,Constants.USER_TYPE_CHIPTRAC);
                }
            }
            else {
                // Load all users
                userList = UserDAO.loadAllUsers(true/*load expired and disabled users*/,Constants.USER_TYPE_CHIPTRAC);
            }

            if (session.getAttribute("groupList") == null) {
                // Load group list and add it to session
                groupList = UserDAO.loadAllUserGroups();
            }

            if (userList != null) {
                session.setAttribute ("userList", userList);
            }

            if (groupList != null) {
                session.setAttribute ("groupList", groupList);
            }
        }
        catch (ScalarException se) {
            // exception while interacting with database
            // log it

            errors.put ("Internal Server Error", "Could not get user list from database");
        }

        return (mapping.findForward("success"));
    }

}